﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using LuaInterface;

public class LuaButtonComponent : MonoBehaviour {

	private Dictionary<LuaFunction, GameObject> functionWithParamGameObject = new Dictionary<LuaFunction, GameObject> ();

	private Button button;

	private Button GetButton() {
		if (button != null)
			return button;

		button = GetComponent<Button> ();
		if (button != null) {
			button.onClick.AddListener (OnButtonClick);
		} else {
			Debug.LogWarning ("LuaButtonComponent doesn't attach to a GameObject with Button Component!");
		}

		return button;
	}

	public void AddBtnClickGameObject(LuaFunction func, GameObject obj) {
		if (func == null || obj == null) {
			Debug.LogWarning ("LuaButtonComponent AddButtonClick, param is null!");
			return;
		}

		Button btn = GetButton ();
		if (btn != null) {
			GameObject obj1 = null;
			if (functionWithParamGameObject.TryGetValue (func, out obj1)) {
				if (obj1 != obj) {
					functionWithParamGameObject [func] = obj;
				}
			} else {
				functionWithParamGameObject.Add (func, obj);
			}
		}
	}

	void OnButtonClick() {
		Debug.Log ("Button clicked! Button name is " + button.name);
		foreach (KeyValuePair<LuaFunction, GameObject> kv in functionWithParamGameObject) {
			kv.Key.Call (kv.Value);
		}
	}

	void OnDestroy() {
		if (button != null) {
			button.onClick.RemoveListener (OnButtonClick);

		}

		functionWithParamGameObject.Clear ();
	}
}
